﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace SerializationStudy
{
    class AttributeSerializable
    {
        public static void Test()
        {
            using (MemoryStream stream = new MemoryStream())
            {
                var formater = new BinaryFormatter();
                formater.Serialize(stream, new TestClassA() { A1 = new TestClassA1 { X = 5 } });

                stream.Position = 0;

                var test = formater.Deserialize(stream) as TestClassA;

                Console.WriteLine(test.A1.X);
            }
        }
    }

    [Serializable]
    public sealed class TestClassA
    {
        public TestClassA1 A1 = new TestClassA1();

        [OnSerializing]
        private void OnSerializing(StreamingContext context)
        {
            Console.WriteLine("TestClassA OnSerializing");
        }

        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
            Console.WriteLine("TestClassA OnSerialized");
        }

        [OnDeserializing]
        private void OnDeserializing(StreamingContext context)
        {
            Console.WriteLine("TestClassA OnDeserializing");
        }

        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            Console.WriteLine("TestClassA OnDeserialized");
        }
    }

    [Serializable]
    public sealed class TestClassA1
    {
        public int X;

        [OnSerializing]
        private void OnSerializing(StreamingContext context)
        {
            Console.WriteLine("TestClassA1 OnSerializing");
        }

        [OnSerialized]
        private void OnSerialized(StreamingContext context)
        {
            Console.WriteLine("TestClassA1 OnSerialized");
        }

        [OnDeserializing]
        private void OnDeserializing(StreamingContext context)
        {
            Console.WriteLine("TestClassA1 OnDeserializing");
        }

        [OnDeserialized]
        private void OnDeserialized(StreamingContext context)
        {
            Console.WriteLine("TestClassA1 OnDeserialized");
        }
    }
}
